package com.example.mybatisplusdemo.web.controller;

import com.example.mybatisplusdemo.common.JsonResponse;
import com.example.mybatisplusdemo.mapper.AirportMapper;
import com.example.mybatisplusdemo.model.domain.Airport;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yrd
 * @since 2025-07-07
 */
@RestController
@RequestMapping("/api/flight")
@RequiredArgsConstructor
public class AirportController {

    private final AirportMapper airportMapper;

    /**
     * 获取城市列表
     * 
     * 业务逻辑说明：
     * 1. 查询所有机场信息
     * 2. 按城市分组，每个城市选择一个代表性机场
     * 3. 返回包含城市名称和机场代码的对象列表
     * 4. 用于前端下拉选择和航班搜索参数构建
     * 
     * @return JsonResponse<Object> 包含城市信息的响应对象
     */
    @GetMapping("/cities")
    public JsonResponse<Object> getCities() {
        try {
            List<Airport> airports = airportMapper.selectList(null);
            
            // 按城市分组，每个城市选择第一个机场作为代表
            List<CityInfo> cities = airports.stream()
                    .collect(Collectors.groupingBy(Airport::getCity))
                    .entrySet().stream()
                    .map(entry -> {
                        String cityName = entry.getKey();
                        Airport representativeAirport = entry.getValue().get(0);
                        return new CityInfo(cityName, representativeAirport.getCode());
                    })
                    .sorted((a, b) -> a.getCity().compareTo(b.getCity()))
                    .collect(Collectors.toList());
                    
            return JsonResponse.success(cities, "城市列表获取成功");
        } catch (Exception e) {
            return JsonResponse.failure("获取城市列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 城市信息内部类
     */
    public static class CityInfo {
        private String city;
        private String code;
        
        public CityInfo(String city, String code) {
            this.city = city;
            this.code = code;
        }
        
        public String getCity() {
            return city;
        }
        
        public void setCity(String city) {
            this.city = city;
        }
        
        public String getCode() {
            return code;
        }
        
        public void setCode(String code) {
            this.code = code;
        }
    }

    /**
     * 获取机场列表
     */
    @GetMapping("/airports")
    public JsonResponse<Object> getAirports() {
        try {
            List<Airport> airports = airportMapper.selectList(null);
            return JsonResponse.success(airports, "机场列表获取成功");
        } catch (Exception e) {
            return JsonResponse.failure("获取机场列表失败: " + e.getMessage());
        }
    }
}
